import React, { useEffect, useState, useCallback } from 'react';
import { getTabThreeData } from '../../request'; // 假设这个函数支持分页
import Masonry from 'react-masonry-css';
import './tab.css';

const TabsThree: React.FC = () => {
  // 存储图片数据
  const [imageData, setImageData] = useState<Array<{ id: string; image: string }>>([]);
  // 当前页码
  const [page, setPage] = useState<number>(1);
  // 是否正在加载更多数据
  const [loading, setLoading] = useState<boolean>(false);
  // 是否还有更多图片
  const [hasMore, setHasMore] = useState<boolean>(true);

  // 处理获取数据的函数
  const fetchData = useCallback(async (page: number) => {
    setLoading(true);
    try {
      const response = await getTabThreeData(page); // 假设这个函数支持分页
      const newData = response.data.list;
      console.log(imageData);
      setImageData((prevData) => {
        // 如果没有更多数据了
        if (newData.length === 0) {
          setHasMore(false);
          return prevData;
        }
        return [...prevData, ...newData];
      });
    } catch (error) {
      console.error('Failed to fetch data:', error);
    } finally {
      setLoading(false);
    }
  }, []);

  // 加载更多数据
  const loadMore = useCallback(() => {
    if (!loading && hasMore) {
      fetchData(page);
      setPage((prevPage) => prevPage + 1);
    }
  }, [fetchData, loading, hasMore, page]);

  // 处理滚动事件
 const handleScroll = (event: React.UIEvent<HTMLDivElement, UIEvent>) => {
    if (window.innerHeight + window.scrollY >=document.documentElement.scrollHeight - 20) {
      loadMore();
    }
  };

  useEffect(() => {
    // 初次加载数据
    fetchData(page);
  }, [fetchData, page]);
  useEffect(()=>{
    window.addEventListener('scroll', handleScroll)
    return () => window.removeEventListener('scroll', handleScroll)
  },[handleScroll])
  // key唯一
  const uniqueKeys = new Set();

  function generateUniqueKey(id) {
    let key = id;
    let count = 1;

    while (uniqueKeys.has(key)) {
      key = `${id}_${count}`;
      count += 1;
    }

    uniqueKeys.add(key);
    return key;
  }
  return (
    <div style={{ width: '100%' }} >
      <Masonry
        breakpointCols={{ default: 6, 1100: 3, 700: 2, 500: 1 }}
        className="my-masonry-grid"
        columnClassName="my-masonry-grid_column"
      >
        {imageData.map(item => (
          <div key={generateUniqueKey(item.id)} style={{ marginBottom: '10px' }}>
            <img
              src={item.image}
              alt="Image"
              style={{ width: '100%', borderRadius: '10px', display: 'block' }}
            />
          </div>
        ))}
      </Masonry>
      {loading && <div className="loading">Loading...</div>}
    </div>
  );
};

export default TabsThree;
